package com.beyondsoft.mcms.domain;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

@RooJavaBean
@RooToString
@RooJpaActiveRecord(finders = { "findFeesByPayerAndPayStatus" })
public class Fee {

    /**
     */
    @NotNull
    @ManyToOne
    private MemberInfo payer;

    /**
     */
    @NotNull
    @ManyToOne
    private Item payStatus;

    /**
     */
    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date periodStartDate;

    /**
     */
    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date periodEndDate;

    /**
     */
    @NotNull
    private BigDecimal amountToPay;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "M-")
    private Date realPayDate;

    /**
     */
    private String transactor;

    /**
     */
    private String contactPhone;

    /**
     */
    @Size(max = 300)
    private String remark;

    /**
     */
    private String createdBy;

    /**
     */
    private String updatedBy;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MM")
    private Date createDate;

    /**
     */
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "MM")
    private Date updateDate;

    public static TypedQuery<Fee> findFeesByPayerAndPayStatus(MemberInfo payer, Item payStatus) {
        EntityManager em = Fee.entityManager();
        StringBuffer sql = new StringBuffer("SELECT o FROM Fee AS o where 1=1 ");
        if (payer != null) {
            sql.append(" and o.payer = :payer ");
        }
        
        if (payStatus != null) {
            sql.append(" and o.payStatus = :payStatus ");
        }
        TypedQuery<Fee> q = em.createQuery(sql.toString(), Fee.class);
        if (payer != null) {
            q.setParameter("payer", payer);
        }
        
        if (payStatus != null) {
            q.setParameter("payStatus", payStatus);
        }
        return q;
    }

    public static void batchAddFee(List<Fee> feeList){
    	EntityManager em = Fee.entityManager();
    	EntityTransaction et = em.getTransaction();
    	et.begin();
    	for (int i=0; i<feeList.size(); i++){
    		
    		em.persist(feeList.get(i));
    		if (i % 20 == 0){
    			em.flush();
    			em.clear();
    		}
    	}
    	
    	et.commit();
    }
    
}
